#include "MyVideoSurface.h"

#include <QVideoSurfaceFormat>

MyVideoSurface::MyVideoSurface(QObject *parent)
    : QAbstractVideoSurface{parent}
{}


QList<QVideoFrame::PixelFormat> MyVideoSurface::supportedPixelFormats(QAbstractVideoBuffer::HandleType type) const
{
    if (type == QAbstractVideoBuffer::NoHandle) {
        return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB32
                                                 << QVideoFrame::Format_ARGB32
                                                 << QVideoFrame::Format_ARGB32_Premultiplied
                                                 << QVideoFrame::Format_RGB565
                                                 << QVideoFrame::Format_RGB555;
    } else {
        return QList<QVideoFrame::PixelFormat>();
    }

}



bool MyVideoSurface::isFormatSupported(const QVideoSurfaceFormat &format) const
{
    return QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat()) != QImage::Format_Invalid;
}



bool MyVideoSurface::start(const QVideoSurfaceFormat &format)
{
    if (isFormatSupported(format) && !format.frameSize().isEmpty()) {
        QAbstractVideoSurface::start(format);
        return true;
    }
    return false;
}



bool MyVideoSurface::present(const QVideoFrame &frame)
{
    if (!frame.isValid()) {
        stop();
        return false;
    }

    if (frame.isMapped()) {
        emit frameAvailable(frame);
    } else {
        QVideoFrame tmpFrame(frame);
        tmpFrame.map(QAbstractVideoBuffer::ReadOnly);
        emit frameAvailable(tmpFrame);
    }

    return true;
}
